﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace OPENXMLLib
{
    public static class CellReferenceUtil
    {
        public static uint GetCellRowIndex(string cellReference)
        {
            string value = Convert.ToString(cellReference);

            Regex regex = new Regex(@"\d+");
            Match match = regex.Match(value);
            return uint.Parse(match.Value);
        }

        public static string GetCellColumnName(string cellReference)
        {
            string value = Convert.ToString(cellReference);

            Regex regex = new Regex("[A-Za-z]+");
            Match match = regex.Match(value);
            return match.Value;
        }

        public static uint GetCellColumnIndex(string cellReference)
        {
            Regex regex = new Regex("[A-Za-z]+");
            Match match = regex.Match(cellReference);
            return (uint)FromAA(match.Value);
        }

        public static string ToAA(int value)
        {
            string AA = string.Empty;
            int d = value / 26;
            int remainder = value % 26;

            if (d == 1 && remainder == 0)
            {
                AA = ToA(26) + AA;
                d = 0;
            }
            else
            {
                AA = ToA(remainder) + AA;
            }

            while (d > 0)
            {
                remainder = d % 26;
                d = d / 26;
                AA = ToA(remainder) + AA;
            }
            return AA;
        }

        private static string ToA(int value)
        {
            if (value <= 0)
            {
                return string.Empty;
            }
            return new string((char)('A' + (value - 1)), 1);
        }

        private static int FromAA(string value)
        {
            int V = 0;

            for (int index = 0; index < value.Length; index++)
            {
                int v = FromA(value[index]);
                if (index == value.Length - 1)
                {
                    V += v;
                }
                else
                {
                    V += (int)Math.Pow(26, index + 1) * v;
                }
            }
            return V;
        }

        private static int FromA(char value)
        {
            return (int)value - (char)'A' + 1;
        }
    }
}
